<!-- src/views/video_add.html -->
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>添加视频</title>
    <!-- 引入 Bootstrap 5 CDN 样式 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

    <!-- 新增：Toast 提示框样式 -->
    <style>
        #toast {
            visibility: hidden;
            min-width: 250px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 4px;
            padding: 16px;
            position: fixed;
            z-index: 9999;
            left: 50%;
            bottom: 30px;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.5s, transform 0.5s;
            font-size: 16px;
        }

        #toast.show {
            visibility: visible;
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }

        #toast.success {
            background-color: #28a745;
        }

        #toast.error {
            background-color: #dc3545;
        }
    </style>
</head>
<body>
    <div id="app" class="container mt-5">
        <h2 class="mb-4">添加新视频</h2>
        <form @submit.prevent="submitVideo" class="row g-3">
            <div class="col-md-6">
                <label class="form-label">视频链接：</label>
                <input type="text" v-model="formData.url" required class="form-control" />
            </div>
            <div class="col-md-6 position-relative">
                <label class="form-label">标题：</label>
                <div class="input-group">
                    <input type="text" v-model="formData.title" required class="form-control" />
                    <button type="button" @click="checkTitle" class="btn btn-outline-primary">检测</button>
                </div>
                <div v-if="titleEmptyError" class="form-text text-danger mt-1">
                    请输入视频标题进行检测
                </div>
                <div v-if="titleExists" class="form-text text-danger mt-1">
                    该视频标题已经存在，继续录入将出现重复内容，请确认
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label">品牌：</label>
                <input type="text" v-model="formData.carBrand" class="form-control" />
            </div>
            <div class="col-md-6">
                <label class="form-label">作者：</label>
                <input type="text" v-model="formData.author" class="form-control" />
            </div>
            <div class="col-md-6">
                <label class="form-label">观看数量（万）：</label>
                <input type="number" v-model.number="formData.views" class="form-control" />
            </div>
            <div class="col-md-6">
                <label class="form-label">评论数量：</label>
                <input type="number" v-model.number="formData.commentCount" class="form-control" />
            </div>
            <div class="col-md-6">
                <label class="form-label">发布时间：</label>
                <input type="date" v-model="formData.publishDate" class="form-control" />
            </div>
            <div class="col-12">
                <button type="submit" :disabled="titleExists" class="btn btn-primary me-2">提交</button>
                <button type="button" @click="goBack" class="btn btn-secondary">返回</button>
            </div>
        </form>
    </div>

    <!-- 新增：Toast 提示框 -->
    <div id="toast"></div>

    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    formData: {
                        url: '',
                        title: '',
                        carBrand: '',
                        author: '',
                        views: null,
                        commentCount: null,
                        publishDate: ''
                    },
                    titleExists: false,
                    titleEmptyError: false // 新增字段：标题为空提示
                };
            },
            methods: {
                // 新增方法：显示 Toast 提示
                showToast(message, type = 'success') {
                    const toast = document.getElementById('toast');
                    toast.textContent = message;
                    toast.className = 'show ' + type; // 显示并设置类型

                    setTimeout(() => {
                        toast.classList.remove('show');
                    }, 3000); // 3秒后自动隐藏
                },
                async submitVideo() {
                    if (this.titleExists) {
                        this.showToast("⚠️ 视频标题已存在，不能提交！", "error");
                        return;
                    }

                    try {
                        const res = await fetch('http://localhost:5000/api/video', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                video_url: this.formData.url,
                                title: this.formData.title,
                                car_brand: this.formData.carBrand,
                                author: this.formData.author,
                                views: this.formData.views,
                                comment_count: this.formData.commentCount,
                                publish_date: this.formData.publishDate
                            })
                        });

                        if (!res.ok) {
                            const errorData = await res.json();
                            throw new Error(errorData.error || `HTTP 错误: ${res.status}`);
                        }

                        const result = await res.json();
                        console.log('✅ 成功添加视频:', result.message);
                        this.showToast("✅ 视频已成功添加", "success");
                        this.formData = {
                            url: '',
                            title: '',
                            carBrand: '',
                            author: '',
                            views: null,
                            commentCount: null,
                            publishDate: ''
                        };
                        this.titleExists = false;
                    } catch (error) {
                        console.error('❌ 提交失败:', error.message);
                        this.showToast("❌ 添加视频失败：" + error.message, "error");
                    }
                },
                goBack() {
                    window.history.back();
                    if (window.history.length <= 1) {
                        window.location.href = '/video_table';
                    }
                },
                async checkTitle() {
                    const trimmedTitle = this.formData.title.trim();

                    // 检查是否为空
                    if (!trimmedTitle) {
                        this.titleEmptyError = true;
                        this.titleExists = false; // 清除旧状态
                        return;
                    } else {
                        this.titleEmptyError = false;
                    }

                    try {
                        const res = await fetch('http://localhost:5000/api/videos');
                        const data = await res.json();

                        const exists = data.some(video => video.video_title === trimmedTitle);

                        this.titleExists = exists;
                    } catch (error) {
                        console.error('❌ 获取视频列表失败:', error);
                        alert("获取视频列表失败，请检查后端是否运行");
                    }
                }
            }
        }).mount('#app');
    </script>
</body>
</html>